package qwq.zyu.CommandblockScan;

import org.bukkit.*;
import org.bukkit.block.BlockState;
import org.bukkit.block.CommandBlock;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;


public class CommandblockScanner implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(ChatColor.RED + "此命令只能由玩家执行！");
            return true;
        }

        Player player = (Player) sender;
        World world = player.getWorld();

        // 扫描整个世界的区块
        int commandBlockCount = 0;
        for (Chunk chunk : world.getLoadedChunks()) {
            for (BlockState blockState : chunk.getTileEntities()) {
                if (blockState instanceof CommandBlock) {
                    CommandBlock cmdBlock = (CommandBlock) blockState;
                    Location loc = cmdBlock.getLocation();
                    String commandText = cmdBlock.getCommand();

                    String message = ChatColor.GOLD + "[命令方块] " +
                            ChatColor.YELLOW + "坐标: " + ChatColor.AQUA + loc.getBlockX() + ", " +
                            loc.getBlockY() + ", " + loc.getBlockZ() +
                            ChatColor.YELLOW + " | 指令: " + ChatColor.GREEN + commandText;

                    // 输出到玩家聊天栏
                    player.sendMessage(message);
                    // 输出到服务器后台日志
                    Bukkit.getLogger().info("[命令方块] 坐标: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + " | 指令: " + commandText);

                    commandBlockCount++;
                }
            }
        }

        if (commandBlockCount == 0) {
            player.sendMessage(ChatColor.RED + "当前世界没有找到命令方块！");
        } else {
            player.sendMessage(ChatColor.GREEN + "共找到 " + commandBlockCount + " 个命令方块！");
        }

        return true;
    }
}